<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>

    var dragEle = {
        target: document.getElementsByClassName('box')[0],
        posX: null,
        poxY: null,
        dragStart: function () {
            this.target._this = this//把这个dragEle的target的元素的_this绑定为dragEle
            this.target.addEventListener('mousedown', this.mouseHandler)
        },
        /*  dragMove: function () {
                this.target.removeEventListener("mousemove", this.mouseHandler)
            },
            dragEnd: function () {
                this.target.removeEventListener("mouseup", this.mouseHandler)
            },都绑定在mouseHandler上面，并不需要在绑定一遍*/
        mouseHandler: function (e) {
            var e = e || window.event
            if (e.type == "mousedown") {
                this._this.posX = e.offsetX
                this._this.posY = e.offsetY
                //这里的this指向target元素(绑定在target上),但之前把target的_this定义为dragEle，所以this._this指向的是dragEle
                document._this = this._this//把document的_this定义为 this_this => target._this=> dragEle
                document.addEventListener("mousemove", this._this.mouseHandler)
                document.addEventListener("mouseup", this._this.mouseHandler)
            } else if (e.type == "mousemove") {
                var e = e || window.event
                var x = e.pageX - this._this.posX
                var y = e.pageY - this._this.posY
                this._this.target.style.left = x + "px"
                this._this.target.style.top = y + "px"
            } else if (e.type == "mouseup") {
                document.removeEventListener("mousemove", this._this.mouseHandler)
                document.removeEventListener("mouseup", this._this.mouseHandler)
            }
        }
    }
    dragEle.dragStart()
</script>

</html>